package com.lovo.service.impl;

import com.lovo.dao.BaseDAO;
import com.lovo.dao.UserDAO;
import com.lovo.dao.impl.UserDAOImpl;
import com.lovo.pojo.UserDO;
import com.lovo.service.UserService;

import javax.swing.*;
import java.sql.Connection;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();
    private BaseDAO baseDAO = new BaseDAO();

    @Override
    public UserDO getByusernameAndPwd(String name, String pwd) {
        return userDAO.getByusernameAndPwd(name, pwd);
    }

    @Override
    public void saveMoney(int id, double money) {
        UserDO userDO = userDAO.getById(id);
        userDO.setMoney(userDO.getMoney() + money);
        userDAO.update(userDO);
    }

    @Override
    public void getMoney(int id, double money) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getMoney() < money) {
            throw new Exception("余额不足");
        }
        user.setMoney(user.getMoney() - money);
        userDAO.update(user);
    }

    @Override
    public void transfer(int id, String name, double money) throws Exception {
        Connection con = null;
        UserDO user = userDAO.getById(id);
        UserDO ortheruser = userDAO.getByUserName(name);
        // 判断账号是否存在
        if (ortheruser == null) {
            throw new Exception("查无此人");
        }
        // 判断是否转给自己
        if (user.getName().equals(name)) {
            throw new Exception("不能转给自己");
        }
        // 判断余额是否足够
        if (money > user.getMoney()) {
            throw new Exception("余额不足");
        }
        // 当期账户扣钱
        user.setMoney(user.getMoney() - money);
        // 对方账户加钱
        ortheruser.setMoney(ortheruser.getMoney() + money);
        try {
            con = baseDAO.getConnection();
            baseDAO.setAutoCommit(false);
            userDAO.update(user);
            userDAO.update(ortheruser);
            baseDAO.commit();
        } catch (Exception e) {
            baseDAO.rollback();
            throw new Exception("转账失败");
        } finally {
            baseDAO.close(con);
        }

    }

    @Override
    public void changeSecret(int id, String oldSecret, String newSecret) throws Exception {
        UserDO user = userDAO.getById(id);
        if (!user.getPwd().equals(oldSecret)){
            throw new Exception("密码错误");
        }
        if (user.getPwd().equals(oldSecret)&&newSecret.matches("^[0-9]{6}$")){
            user.setPwd(newSecret);
            userDAO.update(user);
        }else {
            throw new Exception("密码格式错误");
        }
    }

}
